<!-- 引入命名空间，将静态页面转换为动态的视图 -->
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta content="text/html;charset=UTF-8"></meta>
<meta http-equiv="X-UA-Compatible" content="IE=edge"></meta>
<meta name="viewport" content="width=device-width,initial-scale=1"></meta>

<link th:href="@{asset/bootstrap-3.3.7-dist/css/bootstrap.css}"
	rel="stylesheet"></link>

<link th:href="@{asset/bootstrap-3.3.7-dist/css/bootstrap-theme.css}"
	rel="stylesheet"></link>
<title>Spring boot + WebSocket + 广播模式</title>


</head>
<body onload="disconnect();">
	<noscript>
		<h2 style="color: #ff0000">貌似你的浏览器不支持WebSocket</h2>
	</noscript>
	<div>
		<div>
			<button id="connect" onclick="connect();">连接</button>
			<button id="disconnect" disabled="disabled" onclick="disconnect();">断开连接</button>
		</div>
		<div id="conversationDiv">
			<label>输入你的名字</label> <input type="text" id="name" />
			<button id="sendName" onclick="sendName();">发送</button>
			<p id="response"></p>
		</div>
	</div>
</body>
<script type="text/javascript"
	th:src="@{asset/jquery-3.2.1/jquery-3.2.1.js}"></script>
<script type="text/javascript" th:src="@{asset/websocket/sockjs.js}"></script>
<script type="text/javascript" th:src="@{asset/websocket/stomp.js}"></script>
<script type="text/javascript">
	var stompClient = null;
	function setConnected(connected) {
		document.getElementById('connect').disabled = connected;
		document.getElementById('disconnect').disabled = !connected;
		document.getElementById('conversationDiv').style.visibility = connected ? 'visible'
				: 'hidden';
		$("#response").html();
	}
	function connect() {
		// 连接SocketJS的名称为endpointMessage1
		var socket = new SockJS("/endpointMessage1");
		// 使用STOMP子协议的WebSocket客户端
		stompClient = Stomp.over(socket);
		// 连接ＷｅｂＳｏｃｋｅｔ客户端
		stompClient.connect({}, function(frame) {
			setConnected(true);
			console.log('Connected:' + frame);
			// 通过stompClient.subscribe订阅/topic/getResponse目标发送的消息，这个是在控制器的@SendTo中定义的
			stompClient.subscribe('/topic/getResponse', function(response) {
				console.log("shoudao 收到消息：" + response);
				showResponse(JSON.parse(response.body).responseMessage);
			});
		});
	}

	function disconnect() {
		if (stompClient != null) {
			stompClient.disconnect();
		}
		setConnected(false);
		console.log("释放连接");
	}

	function sendName() {
		var name = $('#name').val();
		console.log("要发送的数据：" + name);
		// 通过 stompClient.send 向、welcome目标发送消息，这个是在控制器的@MessageMapping中定义的
		stompClient.send("/welcome", {}, JSON.stringify({
			'name' : name
		}));
	}

	function showResponse(message) {
		var response = $("#response");
		var text = response.html();
		console.log("原始消息：" + text);
		response.html(message + text);
	}
</script>

</html>